﻿using Batman.Identity.Data;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Identity.Controllers
{
    public class WeixinAccountController : Controller
    {
        private readonly IIdentityServerInteractionService _interaction;
        private readonly IAuthenticationSchemeProvider _schemeProvider;
        private readonly IEventService _events;
        private readonly UserManager<BatmanUser> _userManager;
        private readonly SignInManager<BatmanUser> _signInManager;

        public WeixinAccountController(
            IIdentityServerInteractionService interaction,
            IAuthenticationSchemeProvider schemeProvider,
            IEventService events,
            UserManager<BatmanUser> userManager,
            SignInManager<BatmanUser> signInManager
            )
        {
            // if the TestUserStore is not in DI, then we'll just use the global users collection
            // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
            _userManager = userManager;
            _signInManager = signInManager;
            _interaction = interaction;
            _schemeProvider = schemeProvider;
            _events = events;
        }

        /// <summary>
        /// 用微信openId登录
        /// </summary>
        /// <param name="weixinOpenId"></param>
        /// <param name="nickname"></param>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public async Task<IActionResult> Login(string weixinOpenId, string nickname, string clientId)
        {
            var findResult = _userManager.Users.AsNoTracking().FirstOrDefault(t => t.WxOpenId == weixinOpenId);
            if (findResult == null)
            {
                // 数据库中不存在用户，注册新建
                var newUser = new BatmanUser
                {
                    UserName = nickname,
                    WxOpenId = weixinOpenId
                };

                var hashResult = await _userManager.HasPasswordAsync(newUser);

                var crateResult = await _userManager.CreateAsync(newUser);

                return Json(new
                {
                    userId = newUser.Id
                });
            }

            return Json(new
            {
                userId = findResult.Id
            });
        }
    }
}
